<template>
  <div class="work-modal">
    <!-- 工作集信息修改 Start -->
    <a-modal
      :title="workEdit ? '修改工作集' : workCopy ? '复制工作集' : '新增工作集'"
      :visible="workShow"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model
        layout="horizontal"
        :model="workData"
        :rules="workFormRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 14 }"
        ref="workForm"
      >
        <a-form-model-item label="工作集类型">
          <a-select
            :disabled="!workEdit && !workCopy"
            show-search
            v-model="workData.JobGroupTypeID"
            :filter-option="false"
            @popupScroll="handlePopupScroll"
            @search="handleSearch"
          >
            <a-select-option
              v-for="i in workTypeList"
              :value="i.JobGroupTypeID"
              :key="i.JobGroupTypeID"
              >{{ i.JobGroupTypeName }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="工作集名称" prop="JobGroupName">
          <a-input allow-clear v-model="workData.JobGroupName" />
        </a-form-model-item>

        <a-form-model-item label="工作集编码">
          <a-input allow-clear v-model="workData.JobGroupNo" />
        </a-form-model-item>
        <a-form-model-item label="版本号">
          <a-input allow-clear v-model="workData.JobTempletVisionOut" />
        </a-form-model-item>
        <a-form-model-item label="工作集描述">
          <a-textarea style="resize: none" v-model="workData.JobGroupDesc" />
        </a-form-model-item>
        <a-form-model-item label="工作集备注">
          <a-textarea style="resize: none" v-model="workData.Remark" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 工作集信息修改 End -->
  </div>
</template>

<script>
import {
  addJobGroup,
  updateJobGroup,
  copyJobGroup,
} from "@/api/JobGroup/index";
import { getJobGroupTypeDtos } from "@/api/JobGroupType/index"; //工作集类型
export default {
  props: ["workShow", "workEdit", "workData", "workCopy"],
  data() {
    return {
      workTypeItem: {}, //工作集类型
      workTypeList: [], //工作集列表
      selectTemaplateSearch: {
        keyWord: null,
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 10,
        },
      }, //下拉框工作类型搜搜参数
      confirmLoading: false, //提交按钮Loading
      workFormRules: {
        JobGroupName: [
          {
            required: true,
            message: "请填写工作集名称",
            trigger: "blur",
            help: "",
          },
        ],
      }, //校验项
    };
  },
  methods: {
    //提交函数
    handleOk() {
      this.confirmLoading = true;
      try {
        this.$refs.workForm.validate(async (valid) => {
          if (valid) {
            if (this.workEdit) {
              let res = await updateJobGroup(this.workData);
              res.Success
                ? this.$message.success("修改成功")
                : this.$message.error(res.Message);

              this.handleCancel();
              this.closeCheck();
              this.updWork();
            } else if (this.workCopy) {
              let res = await copyJobGroup(this.workData);
              res.Success
                ? this.$message.success("复制成功")
                : this.$message.error(res.Message);

              this.handleCancel();
              this.closeCheck();
              this.updWork();
              //复制工作集
            } else {
              let res = await addJobGroup(this.workData);
              res.Success
                ? this.$message.success("新增成功")
                : this.$message.error(res.Message);

              this.handleCancel();
              this.closeCheck();
              this.updWork();
            }
          }
        });
      } catch (error) {
      } finally {
        this.confirmLoading = false;
      }
    },
    //关闭弹窗
    handleCancel() {
      this.closeCheck();
      this.$emit("update:workShow", false);
    },
    //清除校验
    closeCheck() {
      this.$refs.workForm.clearValidate();
    },
    //获取工作集类型
    async getJobGroupTypeDtos() {
      let res = await getJobGroupTypeDtos(this.selectTemaplateSearch);
      if (res.Success) {
        this.workTypeItem = res.Data;
        const newItems = res.Data.Data.filter(
          (newItem) =>
            !this.workTypeList.find(
              (existingItem) =>
                existingItem.JobGroupTypeID === newItem.JobGroupTypeID
            )
        );
        // 合并新元素到 this.workTypeList
        this.workTypeList = [...this.workTypeList, ...newItems];

        let flag = this.workTypeList.some(
          (item) => item.JobGroupTypeID === this.workData.JobGroupTypeID
        );

        if (!flag) {
          this.onceMoreJobGroupTypeDtos();
        }
      }
    },
    //滚动至底部
    handlePopupScroll(e) {
      const { target } = e;
      const { scrollTop, scrollHeight, clientHeight } = target;

      if (scrollTop + clientHeight >= scrollHeight - 1) {
        // 已经到达底部，触发分页逻辑
        // todo 这里就可以触发加载下一页请求  具体函数根据当前业务需求来定
        // 判断当前列表项条数是否与总条数相等
        if (this.workTypeList.length >= this.workTypeItem.TotalNumber) {
          return;
        } else {
          this.selectTemaplateSearch.pageRequestModel.pageIndex++;
          this.getJobGroupTypeDtos();
        }
      }
    },
    //搜索
    async handleSearch(value) {
      let res = await getJobGroupTypeDtos({
        keyWord: value,
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 10,
        },
      });
      if (res.Success) {
        this.workTypeItem = res.Data;
        this.workTypeList = res.Data.Data;
      }
    },

    //重新查找选中项
    async onceMoreJobGroupTypeDtos() {
      let res = await getJobGroupTypeDtos({
        keyWord: this.workData.JobGroupTypeName,
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 1,
        },
      });
      if (res.Success) {
        // 过滤掉 this.workTypeList 中已存在的元素
        const newItems = res.Data.Data.filter(
          (newItem) =>
            !this.workTypeList.find(
              (existingItem) =>
                existingItem.JobGroupTypeID === newItem.JobGroupTypeID
            )
        );
        // 合并新元素到 this.workTypeList
        this.workTypeList = [...newItems, ...this.workTypeList];
      }
    },

    //更新工作集信息
    updWork() {
      this.$emit("updWorkFun");
    },
  },
  watch: {
    workShow: {
      handler(newVal, oldValue) {
        if (newVal) {
          this.getJobGroupTypeDtos();
        }
      },
      deep: true,
    },
  },
};
</script>

<style lang="less" scoped></style>
